import datetime
import json
import re
from django.http import JsonResponse
from django.shortcuts import render
from django.utils import timezone
from django.views import View

from ajia08.utils.qiniuyun.qiniu_storage import QINIUYUN_URL
from ajia08.utils.views import LoginRequiredMixin
# Create your views here.
from lhc_order.models import Order
from test_xianghaiyang.models import House
from xiejian_user.models import User

"""添加订单&获取订单列表"""
class AddOrder(LoginRequiredMixin, View):

    """添加订单"""
    def post(self, request):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        house_id = json_dict.get('house_id')
        print(house_id)
        start_date = json_dict.get('start_date')
        end_date = json_dict.get('end_date')

        # 判断参数是否齐全
        if not all([house_id, start_date, end_date]):
            return JsonResponse({'errno': "4103",
                                 'errmsg': '缺少必传参数'})

        # house_id校验
        try:
            House.objects.get(id=house_id)
        except Exception as e:
            return JsonResponse({'errno': "4001",
                                 'errmsg': '房源查询错误'})

        # start_date校验
        data_start = datetime.datetime.strptime(start_date,"%Y-%m-%d")
        data_end = datetime.datetime.strptime(end_date,"%Y-%m-%d")
        if data_end == data_start:
            return JsonResponse({'errno': "4103",
                                 'errmsg': '时间不能相同'})
        orders = Order.objects.filter(house_id=house_id)

        # 判断入住时间是否与房屋其他(全部)订单冲突
        for order in orders:
            # print(data_start,order.begin_date)
            a = data_start.date()
            if a < order.end_date and a >= order.begin_date:
                return JsonResponse({'errno': "4202",
                                     'errmsg': '该时间段房屋已预订'})

        # 订单保存到数据库
        # 获取登录用户id
        user = request.user.id

        # 预订天数
        days = data_end - data_start

        try:
            # 房屋单价
            house= House.objects.get(id=house_id)
            house_price = house.price


        except Exception as e:
            return JsonResponse({'errno': "4001",
                                 'errmsg': '获取房屋单价出错'})


        try:
            # 保存订单基本信息 Order
            order = Order.objects.create(
                user_id=user,
                house_id=house_id,
                begin_date=start_date,
                end_date=end_date,
                days=days.days,
                house_price=house_price,
                amount=days.days * house_price,
            )
            res = Order.objects.filter(house_id=house_id)
            res = len(res)
            house=House.objects.filter(id=house_id,
                                       order_count=0).update(order_count=res)

        except Exception as e:
            return JsonResponse({'errno': '4004',
                                 'errmsg': '保存订单出错'})

        # 保存订单
        # order.save()
        # house.save()
        # 响应结果
        return JsonResponse({"data": {"order_id": order.id},
                             "errno": "0",
                             "errmsg": "下单成功"
                            })

    """查询订单列表"""
    def get(self, request):
        """查询订单列表"""


        # 判断用户身份
        role = request.GET.get('role')
        # 测试用身份
        # role = 'landlord'
        # 用户身份为顾客
        if role == 'custom':
            user_id = request.user.id
            # 测试订单，数据库数据用户编号位3
            # user_id = 3
            try:
                orders = Order.objects.filter(user_id=user_id)
            except Exception as e:
                return JsonResponse({'errno': "4001",
                                     'errmsg': '订单查询错误'})

            order_list = []
            for order in orders:
                status = order.status
                stattus_data = Order.ORDER_STATUS_CHOICES[status]
                order_list.append({
                    "amount": order.amount,
                    "comment": order.comment,
                    "ctime": order.create_time,
                    "days": order.days,
                    "end_date": order.end_date,
                    "img_url": QINIUYUN_URL+str(order.house.index_image_url),
                    "order_id": order.id,
                    "start_date": order.begin_date,
                    "status": stattus_data[1],
                    "title": order.house.title
                })
            if len(order_list)==0:
                return JsonResponse({
                                     "errmsg": "无数据",
                                     "errno": "4002"})

            order_dir = {"orders": order_list}

            return JsonResponse({"data": order_dir,
                                 "errmsg": "OK",
                                 "errno": "0"})
        # 用户身份位房东
        if role == 'landlord':
            print(request.user.id_card)
            if not request.user.id_card:
                return JsonResponse({'errno': "4105",
                                     'errmsg': '未实名'})

            user_id = request.user.id
            # user_id = 9
            try:
                house = House.objects.filter(user_id=user_id)
                order_list = []
                for house_id in house:
                    try:
                        orders = Order.objects.filter(house_id=house_id.id)
                        if orders:
                            for order in orders:
                                status = order.status
                                stattus_data = Order.ORDER_STATUS_CHOICES[status]
                                order_list.append({
                                    "amount": order.amount,
                                    "comment": order.comment,
                                    "ctime": order.create_time,
                                    "days": order.days,
                                    "end_date": order.end_date,
                                    "img_url": QINIUYUN_URL+str(order.house.index_image_url),
                                    "order_id": order.id,
                                    "start_date": order.begin_date,
                                    "status": stattus_data[1],
                                    "title": order.house.title
                                })
                        else:
                            continue
                    except Exception as e:
                        return JsonResponse({'errno': "4001",
                                             'errmsg': '订单查询错误'})
                if order_list:

                    return JsonResponse({"data": {"orders": order_list},
                                                 "errmsg": "OK",
                                                 "errno": "0"
                                                 })
                else:
                    return JsonResponse({"errmsg": "数据为空",
                                         "errno": "4002"
                                         })



            except Exception as e:
                    return JsonResponse({'errno': "4001",
                                         'errmsg': '订单查询错误'})

'''接单和拒单'''
class SetOrder(LoginRequiredMixin, View):
    '''接单和拒单'''

    def put(self, request, order_id):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        action = json_dict.get('action')
        reason = json_dict.get('reason')

        # 检验参数
        if action is None:
            return JsonResponse({"errno": "4103",
                                 "errmsg": "缺少必传参数"
                                })

        if action == 'accept':
            try:
                # 修改订单状态为待评价
                Order.objects.filter(id=order_id,
                                     status=0).update(
                                     status=3)
            except Exception as e:
                return JsonResponse({"errno": "4004",
                                     "errmsg": "修改订单出错"
                                    })
            return JsonResponse({
                             "errno": "0",
                             "errmsg": "操作成功"
                             })

        if action == 'reject':
            try:
                # 修改订单状态为拒单
                Order.objects.filter(id=order_id,
                                     status=0).update(comment=reason,
                                     status=6)

            except Exception as e:
                return JsonResponse({"errno": "4004",
                                     "errmsg": "修改订单出错"
                                    })
            return JsonResponse({
                             "errno": "0",
                             "errmsg": "操作成功"
                             })

'''评价订单'''
class EvaluationOrder(View):
    '''评价订单'''
    def put(self, request, order_id):
        # 接收参数
        json_dict = json.loads(request.body.decode())
        comment = json_dict.get('comment')

        # 校验参数
        if order_id is None:
            return JsonResponse({
                                 "errno": "4103",
                                 "errmsg": "订单ID参数错误"
                                })
        if type(comment) != type("str"):
            return JsonResponse({
                                 "errno": "4103",
                                 "errmsg": "comment参数错误"
                                })

        try:
            Order.objects.filter(id=order_id).update(comment=comment,
                                                     status=4)

        except Exception as e:
           return JsonResponse({
                                 "errno": "4103",
                                 "errmsg": "comment参数错误"
                                })

        return JsonResponse({
                            "errno": "0",
                            "errmsg": "评论成功"
                            })

"""获取房屋搜索信息"""
class GetHouseInfo(View):
    """获取房屋搜索信息"""
    def get(self,request):

        # 接收参数

        aid = request.GET.get('aid')
        start_date = request.GET.get('sd(start_day)')
        end_date = request.GET.get('ed(end_day)')
        Order_by = request.GET.get('sk(sort_key)')
        page = request.GET.get('p(page)')

        # 根据时间，区域搜索
        if all([aid,start_date,end_date]):

            order = Order.objects.filter(begin_date=start_date, end_date=end_date)
            houses = House.objects.filter(area_id=aid).exclude(id=order.house_id)
            house_list = []
            for house in houses:
                user = User.objects.get(id=house.user_id)
                avatar_url = QINIUYUN_URL + str(user.avatar)
                house_list.append({
                    "address": house.address,
                    "area_name": house.area.name,
                    "ctime": house.create_time,
                    "house_id": house.id,
                    "img_url": QINIUYUN_URL + str(house.index_image_url),
                    "order_count": house.order_count,
                    "price": house.price,
                    "room_count": house.room_count,
                    "title": house.title,
                    "user_avatar": avatar_url
                })
            if len(house_list) == 0:
                return JsonResponse({
                    "errmsg": "无数据",
                    "errno": "4002"
                })
            data_dir = {'houses': house_list, "total_page": 1}
            return JsonResponse({"data": data_dir,
                                 "errmsg": "请求成功",
                                 "errno": "0"
                                 })

        # 只搜索区域
        if aid:
            houses = House.objects.filter(area_id=aid)
            house_list = []
            for house in houses:
                user = User.objects.get(id=house.user_id)
                avatar_url = QINIUYUN_URL + str(user.avatar)
                house_list.append({
                    "address": house.address,
                    "area_name": house.area.name,
                    "ctime": house.create_time,
                    "house_id": house.id,
                    "img_url": QINIUYUN_URL + str(house.index_image_url),
                    "order_count": house.order_count,
                    "price": house.price,
                    "room_count": house.room_count,
                    "title": house.title,
                    "user_avatar": avatar_url
                })
            if len(house_list) == 0:
                return JsonResponse({
                    "errmsg": "无数据",
                    "errno": "4002"
                })
            data_dir = {'houses': house_list, "total_page": 1}
            return JsonResponse({"data": data_dir,
                                 "errmsg": "请求成功",
                                 "errno": "0"
                                 })
        # 只搜索时间
        elif all ([start_date,end_date]):
            order=Order.objects.filter(begin_date=start_date,end_date=end_date)
            houses = House.objects.exclude(id=order.house_id)
            house_list = []
            for house in houses:
                user = User.objects.get(id=house.user_id)
                avatar_url = QINIUYUN_URL + str(user.avatar)
                house_list.append({
                    "address": house.address,
                    "area_name": house.area.name,
                    "ctime": house.create_time,
                    "house_id": house.id,
                    "img_url": QINIUYUN_URL + str(house.index_image_url),
                    "order_count": house.order_count,
                    "price": house.price,
                    "room_count": house.room_count,
                    "title": house.title,
                    "user_avatar": avatar_url
                })
            if len(house_list) == 0:
                return JsonResponse({
                    "errmsg": "无数据",
                    "errno": "4002"
                })
            data_dir = {'houses': house_list, "total_page": 1}
            return JsonResponse({"data": data_dir,
                                 "errmsg": "请求成功",
                                 "errno": "0"
                                 })
        # 搜索所有房屋信息
        else:
            houses = House.objects.all()
            house_list = []
            for house in houses:
                user = User.objects.get(id=house.user_id)
                avatar_url = QINIUYUN_URL + str(user.avatar)
                house_list.append({
                    "address": house.address,
                    "area_name": house.area.name,
                    "ctime": house.create_time,
                    "house_id": house.id,
                    "img_url": QINIUYUN_URL+str(house.index_image_url),
                    "order_count": house.order_count,
                    "price": house.price,
                    "room_count": house.room_count,
                    "title": house.title,
                    "user_avatar": avatar_url
                })
            if len(house_list) == 0:
                return JsonResponse({
                    "errmsg": "无数据",
                    "errno": "4002"
                })
            data_dir = {'houses':house_list, "total_page": 1}
            return JsonResponse({"data": data_dir,
                                 "errmsg": "请求成功",
                                 "errno": "0"
                                 })